package cn.hrc.service.impl;

import cn.hrc.dao.FileMapper;
import cn.hrc.entity.LargeFile;
import cn.hrc.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    FileMapper fileMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Override // 添加图片
    public String addFile( MultipartFile myFile) {
        // 生成唯一ID
        String uuid = UUID.randomUUID().toString()
                .replace("-", "");
        //保存图片信息
        LargeFile lf = new LargeFile();
        try {
            lf.setId(uuid);//唯一ID
            lf.setFilename(myFile.getOriginalFilename());//图片名
            byte[] buf = myFile.getBytes();
            lf.setContent(buf);
            //添加图片
            int n = fileMapper.add(lf);
            if (n == 0) return null;
            logger.info("Redis 添加图片");
            redisTemplate.opsForHash()
                    .put("hrc:file",uuid,lf);
        } catch (IOException e) {
            System.out.println("图片上传失败");
            return null;
        }
        logger.info("图片上传成功");
        // 返回图片ID
        return uuid;
    }
    @Override // 修改图片
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public String updFile(MultipartFile myFile, String id) {
        logger.info("修改图片 Redis 双删");
        String uuid = UUID.randomUUID().toString()
                .replace("-", "");
        //保存图片信息
        LargeFile lf = new LargeFile();
        try {
            lf.setId(uuid);//唯一ID
            lf.setFilename(myFile.getOriginalFilename());//图片名
            byte[] buf = myFile.getBytes();
            lf.setContent(buf);
            //
            System.out.println("修改图片  双删方法");
            delFile(id);
            int n = fileMapper.add(lf);
            if (n == 0) return null;
            logger.info("Redis 添加图片");
            redisTemplate.opsForHash()
                    .put("hrc:file",uuid,lf);
        } catch (IOException e) {
            System.out.println("图片上传失败");
            return null;
        }
        return uuid;
    }

    @Override
    public void delFile(String id) {
        logger.info("删除图片 Redis 双删");
        redisTemplate.opsForHash()
                .delete("hrc:file",id);
        logger.info("数据库删除图片");
        fileMapper.delete(id);
        logger.info("Redis 删除图片");
        redisTemplate.opsForHash()
                .delete("hrc:file", id);
        logger.info("Redis 删除图片完成");
    }
}
